# Copyright (c) 2014 Joseph Armbruster
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import os
import sys
import urllib2
import ConfigParser

if __name__ == '__main__':

	config_filename = 'agg.cfg'

	if len(sys.argv) == 2:
		config_filename = sys.argv[1]

	print '[option] configuration file: %s' % (config_filename)

	if not os.path.exists(config_filename):
		print '[error] unable to find configuration file'
		sys.exit(-1)

	keps = {}
	try:
		print '[info] reading config file'

		config = ConfigParser.ConfigParser()
		config.read(config_filename)

		# read the configuration file sections
		for section in config.sections():

			print '[info] processing section: %s' % (section)
			sats = []

			if os.path.exists(section):
				print '[info] found keps file on disk, reading: %s' % (section)
				section_keps = open(section).readlines()
			else:
				print '[info] downloading keps from: %s' % (section)
				section_keps  = urllib2.urlopen(section).readlines()

			if not config.has_option(section, 'sats'):
				print '[error] section is missing sats listing'

			sats = config.get(section, 'sats').split(',')
			print '[info] reading sats: %s' % (sats)
			sats = [item.strip().lower() for item in sats]

			section_keps = [line.strip() for line in section_keps]
	                section_keps = [ [section_keps[i], section_keps[i+1], section_keps[i+2]] for i in xrange(0, len(section_keps), 3)]

			print '[info] read %d keps from source' % (len(section_keps))

			keps[section] = [sats, section_keps]

		# grab the keps of interest
		all_keps = {}
		for source in keps:
			print 'processing source: %s' % (source)

			section = keps[source]

			section_sats = section[0]
			section_keps = section[1]	
			for kep in section_keps:
				if kep[0].lower() in section_sats:
					all_keps[kep[0]] = [kep[0], kep[1], kep[2]]

		# sort all the keps by satellite name
		aggregate = ''
		sorted_keys = all_keps.keys()
		sorted_keys.sort()
		for key in sorted_keys:
			kep = all_keps[key]	
			aggregate += '%s\n%s\n%s\n' % (kep[0], kep[1], kep[2])
		open('all.tle','w').write(aggregate)
	
	except Exception, e:
		print '[error] details: %s' % (str(e))
